import { loginApi, logoutApi } from "@/api/auth";
import { getPortalUserInfo, getUserInfoApi } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";
import defaultSettings from "@/settings";

const initUserData: any = {
  roles: [],
  perms: [],
};

export const useUserStore = defineStore("user", () => {
  const user = ref<UserInfo>({
    roles: [],
    perms: [],
  });
  const token: any = useStorage<string>("token", "");
  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          const { tokenType, accessToken } = response.data;
          localStorage.setItem("token", tokenType + "=" + accessToken); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          console.log(response);
          const d: Date = new Date();
          d.setTime(d.getTime() + 10 * 24 * 60 * 60 * 1000);
          const expires: string = "expires=" + d.toUTCString();
          // @ts-ignore
          token.value = accessToken;
          document.cookie = "token=" + accessToken + "; " + expires + ";path=/";
          // localStorage.setItem("token", "token=" + accessToken);
          resolve();
        })
        .catch((error) => {
          ElMessage({
            showClose: true,
            type: "error",
            message: error,
          });
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  /* function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfoApi()
        .then(({ data }) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          if (!data.roles || data.roles.length <= 0) {
            reject("getUserInfo: roles must be a non-null array!");
            return;
          }
          Object.assign(user.value, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }*/

  function getUserToken() {
    return token.value;
  }

  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getPortalUserInfo()
        .then(({ data }: { data: any }) => {
          if (!data) {
            console.log("获取登录信息异常" + data);
            reject("Verification failed, please Login again.");
            return;
          }
          const userInfo: any = {};
          // 要保证返回的是UserInfo
          userInfo.userId = data.entity.id;
          userInfo.username = data.entity.account;
          userInfo.nickname = data.entity.name;
          userInfo.avatar = "";
          userInfo.roles = ["ADMIN"];
          userInfo.perms = [
            "sys:menu:delete",
            "sys:dept:edit",
            "sys:dict_type:add",
            "sys:dict:edit",
            "sys:dict:delete",
            "sys:dict_type:edit",
            "sys:menu:add",
            "sys:user:add",
            "sys:role:edit",
            "sys:dept:delete",
            "sys:user:password_reset",
            "sys:user:edit",
            "sys:user:delete",
            "sys:dept:add",
            "sys:role:delete",
            "sys:dict_type:delete",
            "sys:menu:edit",
            "sys:dict:add",
            "sys:role:add",
          ];
          Object.assign(user.value, { ...userInfo });
          console.log("用户信息:" + JSON.stringify(user.value));
          resolve(user.value);
        })
        .catch((error: any) => {
          console.log("portal接口请求异常," + error);
          reject(error);
        });
    });
  }

  // user logout
  function logout() {
    Object.assign(user.value, { ...initUserData });
    document.cookie = "token=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
    localStorage.setItem("token", "");
    location.reload(); // 清空路由
    /* return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {

          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });*/
  }

  // remove token
  function resetToken() {
    console.log("resetToken");
    Object.assign(user.value, { ...initUserData });
    return new Promise<void>((resolve) => {
      localStorage.setItem("token", "");
      resetRouter();
      resolve();
    });
  }

  return {
    user,
    login,
    getUserInfo,
    getUserToken,
    logout,
    resetToken,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
